import { resourceEntApi } from '@/api';
import { EnCourseWareGroup, EnResourceNameGroup, pageOpeTypeEnum } from '@/common';
import { useAppSelector } from '@/redux/store';
// import ExaminationBatchUpload from '@/components/resourceLibraryComp/ExaminationAddOrEditComp/ExaminationBatchUpload';
import JudgeExaminationItem from '@/components/resourceLibraryComp/ExaminationAddOrEditComp/JudgeExaminationItem';
import { Button, Form, message } from 'antd';
import { useEffect, useMemo, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { YmAddPageLayout, type YmAddPageLayoutProps } from 'ym-design';

const formItemLayout = {
  labelCol: { span: 2 },
  wrapperCol: { span: 18 },
};

const SELECTITEMLIST = [
  { itemCode: '0', itemValue: '错' },
  { itemCode: '1', itemValue: '对' },
];

const { PaneItem } = YmAddPageLayout;

const plantType = process.env.processEnvDetail.REACT_APP_PLATFORM;
function AddJudgeQue() {
  const [searchParam] = useSearchParams();
  const navigator = useNavigate();
  const type = searchParam.get('type');
  const parentId = searchParam.get('parentId');
  const { entId } = useAppSelector((state) => state.loginEnt);
  const examinationId = searchParam.get('resourceId');
  const [collPanesActiveKeys, setCollPanesActiveKeys] = useState([0, -1]); // 打开的题目的keys
  const [form] = Form.useForm();
  const [loadingDetail, setLoadingDetail] = useState({
    subBtnDis: false,
    viewLoading: false,
  });

  const goBackToList = () => {
    const x = plantType === 'boss' ? '/resourceLibrary/' : '/cusResLib/';
    navigator(x + 'examination', { state: { activeTab: 'judgeQue' } });
  };

  // 添加题目
  const addQuestion = () => {
    const { examinationList } = form.getFieldsValue();
    const currActiveExaFieldIndex = examinationList.length;
    form.setFieldsValue({
      examinationList: [...examinationList, { content: undefined }],
    });
    collPanesActiveKeys.push(currActiveExaFieldIndex);
    const newArr = Array.from(new Set<number>([...collPanesActiveKeys]));
    setCollPanesActiveKeys(newArr);
  };

  // 删除题目
  const handleRemoveExamination = (exaIndex: number) => {
    const { examinationList } = form.getFieldsValue();
    examinationList.splice(exaIndex, 1);
    form.setFieldsValue({
      examinationList: [...examinationList],
    });
  };

  /**
   *  批量上传题目
   * @param newExaminationList
   * @param type  1:覆盖，2：追加
   */
  const handleSetFormValues = (newExaminationList: any[], type: number) => {
    const currExaminationList = form.getFieldValue('examinationList');
    const tempExaminationList = type === 1 ? newExaminationList : [...currExaminationList, ...newExaminationList];
    form.setFieldValue('examinationList', tempExaminationList);
    const tempCollPanesActiveKeys = tempExaminationList.map((listItem: any, index: number) => index);
    setCollPanesActiveKeys([...tempCollPanesActiveKeys, -1]);
  };

  // 当前题目不在 collPanesActiveKeys中时，有error，就要打开
  function _openErrorExaminationPane(err: any) {
    const { errorFields } = err;
    const errorStr: string = errorFields[0].errors[0];
    const kuo1 = errorStr.indexOf('【');
    const kuo2 = errorStr.indexOf('】');
    const currNumber = Number(errorStr.substring(kuo1 + 1, kuo2));
    const errorIndex = collPanesActiveKeys.findIndex((val) => val === currNumber);
    if (errorIndex > -1) return;
    collPanesActiveKeys.push(currNumber);
    const newArr = Array.from(new Set<number>([...collPanesActiveKeys]));
    setCollPanesActiveKeys(newArr);
  }

  // 提交
  const formSub = () => {
    setLoadingDetail({ subBtnDis: true, viewLoading: true });
    form
      .validateFields()
      .then((values) => {
        // console.log('--AddJudge--values--:', values);
        const { examinationList } = values;
        const quesArrs = examinationList.map((listItem: any) => {
          const { content, anwserItemList } = listItem;
          return {
            content,
            // anwserItemList: [anwserItemList],
            answerItemList: [anwserItemList],
            questionType: '300',
            sourceType: '100',
            entId,
            selectItemList: SELECTITEMLIST,
            parentId,
            // type: '300',
          };
        });
        const subData = {
          crateQuestionDtoList: [],
        };
        subData.crateQuestionDtoList = quesArrs;
        console.log('--AddJudge--subData--:', subData);
        let requestApi;
        if (type === pageOpeTypeEnum['add']) {
          requestApi = resourceEntApi.createExamination(subData);
        } else if (type === pageOpeTypeEnum['edit']) {
          const editSubData = subData.crateQuestionDtoList[0];
          editSubData.questionId = examinationId;
          requestApi =
            plantType === 'boss'
              ? resourceEntApi.updateExamination(editSubData)
              : resourceEntApi.createExamination(subData);
        } else {
          return message.error('type 未定义');
        }
        requestApi
          .then((res: any) => {
            const { code, msg } = res;
            if (code === '200') {
              message.success(msg || `${type === pageOpeTypeEnum['add'] ? '添加' : '编辑'}成功`);
              //保存
              goBackToList();
            } else {
              message.error(msg);
            }
          })
          .catch((err: any) => {
            console.log('--AddJudge--_formSub--err--:', err);
          })
          .finally(() => {
            setLoadingDetail({ subBtnDis: false, viewLoading: false });
          });
      })
      .catch((err) => {
        console.log('--AddJudge--form--err--:', err);
        setLoadingDetail({ subBtnDis: false, viewLoading: false });
        _openErrorExaminationPane(err);
      });
  };

  const operationFooter = useMemo(() => {
    const operationBtn = [
      <Button key="subOnce" type="primary" size="small" disabled={loadingDetail.subBtnDis} onClick={formSub}>
        保存
      </Button>,
    ];
    if (type === pageOpeTypeEnum['add']) {
      operationBtn.unshift(
        <Button key="addExa" type="primary" size="small" disabled={loadingDetail.subBtnDis} onClick={addQuestion}>
          添加考题
        </Button>,
      );
    }
    return operationBtn;
  }, [type, loadingDetail, collPanesActiveKeys]);

  useEffect(() => {
    if (type === pageOpeTypeEnum['add']) {
      form.setFieldsValue({
        examinationList: [{ content: undefined }],
      });
    } else {
      resourceEntApi.getExaminationById({ questionId: examinationId }).then((res: any) => {
        // console.log('--Examination--res--:', res);
        const {
          data: { content, answerList },
        } = res;
        let anwserItemList: any[] = [];
        try {
          anwserItemList = answerList[0];
        } catch (err) {
          console.log('---Examination--jsonParse--err--:', err);
        }
        const tempExaminationList = [{ content, anwserItemList }];
        form.setFieldValue('examinationList', tempExaminationList);
      });
    }
  }, []);

  const layoutParams: YmAddPageLayoutProps = useMemo(
    () => ({
      leftOperation: {
        onBack: () => {
          goBackToList();
        },
      },
      rightOperationDom: operationFooter,
      destroyInactiveTabPane: false,
    }),
    [operationFooter],
  );

  return (
    <YmAddPageLayout {...layoutParams}>
      <PaneItem
        tabKey="tab1"
        label={
          (type === pageOpeTypeEnum['add'] ? '添加' : '编辑') +
          '考题（' +
          EnResourceNameGroup[Number(EnCourseWareGroup['judgeQue'])] +
          '）'
        }
        className="pane_tab1"
      >
        <div className="ym_detail_grid">
          <Form layout="horizontal" labelAlign="right" size="large" form={form} {...formItemLayout}>
            <Form.List name="examinationList">
              {(exaFields, { add: exaAdd, remove: exaRemove, move: exaMove }, { errors }) =>
                exaFields.map((exaField, exaIndex) => (
                  <JudgeExaminationItem
                    title={`题目${exaIndex + 1}`}
                    key={exaField.key}
                    exaField={exaField}
                    exaFields={exaFields}
                    exaIndex={exaIndex}
                    collPanesActiveKeys={collPanesActiveKeys}
                    onSetCollPanesActiveKeys={setCollPanesActiveKeys}
                    onRemoveExamination={handleRemoveExamination}
                  />
                ))
              }
            </Form.List>
          </Form>
        </div>
      </PaneItem>
    </YmAddPageLayout>
  );
}

export default AddJudgeQue;
